﻿using Parylene_CVD.Commands;
using Parylene_CVD.DAL;
using Parylene_CVD.Model.DModels;
using Parylene_CVD.Service;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Parylene_CVD.Views;

namespace Parylene_CVD.ViewModel
{
    public class DeviceManagementViewModel : ViewModelBase
    {
        DeviceDAL deviceDAL = new DeviceDAL();
        public DeviceManagementViewModel(NavigationService HomeViewNavigationService, NavigationService AddDeviceViewNavigationService)
        {
            dataSource = deviceDAL.GetAllDevice();
            ComboBoxCommand = new DelegateCommand<Object>(ComboBoxSelectionChanged);
            NextPageCmd = new DelegateCommand(NextPage);
            PreviousPageCmd = new DelegateCommand(PreviousPage);
            LastPageCmd = new DelegateCommand(LastPage);
            FirstPageCmd = new DelegateCommand(FirstPage);
            ExitCommand = new NavigateCommand(HomeViewNavigationService);
            AddDeviceCommand = new NavigateCommand(AddDeviceViewNavigationService);
            DeleteCommand = new RelayCommand(DeleteDevice);
            EditCommand = new RelayCommand(EditDevice);
            CreateDevices();
        }

        public ICommand ExitCommand { get; set; }
        public ICommand AddDeviceCommand { get; set; }
        // DeleteCommand用于删除操作
        public ICommand DeleteCommand { get; }
        public ICommand EditCommand { get; set; }
        public List<Device> dataSource { get; set; }

        /// <summary>
        /// 页容量初始化
        /// </summary>
        public int pagesize = 10;
        /// <summary>
        /// 最后一页事件
        /// </summary>
        public DelegateCommand LastPageCmd { get; private set; }
        /// <summary>
        /// 第一页事件
        /// </summary>
        public DelegateCommand FirstPageCmd { get; private set; }
        /// <summary>
        /// 上一页事件
        /// </summary>
        public DelegateCommand PreviousPageCmd { get; private set; }
        /// <summary>
        /// 下一页事件
        /// </summary>
        public DelegateCommand NextPageCmd { get; private set; }


        /// <summary>
        /// 下拉事件
        /// </summary>
        public DelegateCommand<Object> ComboBoxCommand { get; private set; }
        /// <summary>
        /// 第几页
        /// </summary>
        private int pageNumber;

        public int PageNumber
        {
            get { return pageNumber; }
            set
            {
                pageNumber = value;
                OnPropertyChanged(nameof(PageNumber));
            }
        }
        /// <summary>
        /// 记录条数
        /// </summary>
        private int totalRecord;

        public int TotalRecord
        {
            get { return totalRecord; }
            set
            {
                totalRecord = value;
                OnPropertyChanged(nameof(TotalRecord));
            }
        }
        /// <summary>
        /// 总页数
        /// </summary>
        private int totalPage;

        public int TotalPage
        {
            get { return totalPage; }
            set
            {
                totalPage = value;
                OnPropertyChanged(nameof(TotalPage));
            }
        }

        /// <summary>
        /// 是否可以执行上一页
        /// </summary>
        private bool canPrevious;

        public bool CanPrevious
        {
            get { return canPrevious; }
            set
            {
                canPrevious = value;
                OnPropertyChanged(nameof(CanPrevious));
            }
        }
        /// <summary>
        /// 是否可以执行上一页
        /// </summary>
        private bool canNext;

        public bool CanNext
        {
            get { return canNext; }
            set
            {
                canNext = value;
                OnPropertyChanged(nameof(CanNext));
            }
        }


        /// <summary>
        /// 分页后的数据
        /// </summary>
        private ObservableCollection<Device> devices;
        public ObservableCollection<Device> Devices
        {
            get { return devices; }
            set { devices = value; OnPropertyChanged(nameof(Devices)); }
        }




        private void FirstPage()
        {
            PageNumber = 1; //增加一页
            CanPrevious = false;
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            TotalRecord = dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Devices = new ObservableCollection<Device>();
            var data = dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Devices.Add(item);
            }
        }

        /// <summary>
        /// 最后一页
        /// </summary>
        private void LastPage()
        {
            CanPrevious = false;
            TotalRecord = dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            PageNumber = TotalPage;//最后一页 将总页码赋值给当前页
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Devices = new ObservableCollection<Device>();
            var data = dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Devices.Add(item);
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        private void NextPage()
        {
            PageNumber++; //增加一页
            CanPrevious = false;
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            TotalRecord = dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Devices = new ObservableCollection<Device>();
            var data = dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Devices.Add(item);
            }
        }

        private void PreviousPage()
        {
            PageNumber--; //增加一页
            CanPrevious = false;
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            TotalRecord = dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Devices = new ObservableCollection<Device>();
            var data = dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Devices.Add(item);
            }
        }

        /// <summary>
        /// 选择每页显示记录数
        /// </summary>
        /// <param name="obj"></param>
        private void ComboBoxSelectionChanged(Object obj)
        {
            if (obj != null)
            {
                var Content = ((System.Windows.Controls.ContentControl)obj).Content;
                switch (Content)
                {
                    case "10条/页": pagesize = 10; ComboBoxSelectionInitData(); break;
                    case "20条/页": pagesize = 20; ComboBoxSelectionInitData(); break;
                    case "30条/页": pagesize = 30; ComboBoxSelectionInitData(); break;
                }
            }
        }

        /// <summary>
        /// 每页显示记录数改变时 重新加载数据
        /// </summary>
        void ComboBoxSelectionInitData()
        {
            //
            PageNumber = 1; //页码改变时 加载第一页
            CanPrevious = false; //是否可以点击上一页 否
            TotalRecord = dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > 1)
            {
                CanNext = true;//是否可以点击下一页
            }
            Devices = new ObservableCollection<Device>();
            var data = dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Devices.Add(item);
            }
        }

        public void CreateDevices()
        {
            PageNumber = 1; //默认加载第一页
            CanPrevious = false; //是否可以点击上一页 否
            TotalRecord = dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > 1)
            {
                CanNext = true;//是否可以点击下一页
            }
            Devices = new ObservableCollection<Device>();
            var data = dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Devices.Add(item);
            }
        }
        /// <summary>
        /// 删除设备后刷新页面数据
        /// </summary>
        public void LoadDevices()
        {
            dataSource = deviceDAL.GetAllDevice();
            Devices = new ObservableCollection<Device>();
            var data = dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Devices.Add(item);
            }
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="deviceName">要删除的设备名</param>
        public void DeleteDevice(object parameter)
        {
            string deviceName = parameter as string;
            if (deviceName != null)
            {
                // 弹出确认框
                var result = MessageBox.Show($"确认删除账号：{deviceName}？", "删除确认", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                if (result == MessageBoxResult.Yes)
                {
                    // 执行删除操作
                    bool success = DeleteDeviceByDeviceName(deviceName);

                    if (success)
                    {
                        MessageBox.Show($"账号：{deviceName} 删除成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                        // 删除成功后可以更新设备列表，或重新加载数据
                        LoadDevices();
                    }
                    else
                    {
                        MessageBox.Show($"删除账号：{deviceName} 失败，请稍后再试。", "失败", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }

        }

        /// <summary>
        /// 从数据库删除设备
        /// </summary>
        /// <param name="deviceName">删除的设备名</param>
        /// <returns>true表示删除成功，false表示失败</returns>
        private bool DeleteDeviceByDeviceName(string deviceName)
        {
            return deviceDAL.DeleteDevice("deviceName = '" + deviceName + "'");
        }

        // 编辑设备方法
        private void EditDevice(object parameter)
        {
            string deviceName = parameter as string;
            if (deviceName != null)
            {
                // 找到要编辑的设备
                Device deviceToEdit = Devices.FirstOrDefault(u => u.DeviceName == deviceName);

                if (deviceToEdit != null)
                {
                    //拷贝对象传入，否则会造成页面数据不一致
                    Device deviceCopy = new Device
                    {
                        DeviceId = deviceToEdit.DeviceId,
                        IP = deviceToEdit.IP,
                        DeviceName = deviceToEdit.DeviceName,
                        Port = deviceToEdit.Port,
                        UpdateTime = deviceToEdit.UpdateTime,
                        CreateTime = deviceToEdit.CreateTime,
                    };
                    // 弹出编辑窗口（模态对话框）
                    EditDevice editWindow = new EditDevice(deviceCopy); // 传入要编辑的设备信息
                    bool? result = editWindow.ShowDialog(); // 显示窗口并等待结果

                    if (result == true)
                    {
                        // 更新成功后刷新数据
                        LoadDevices();
                        MessageBox.Show($"设备 {deviceName} 修改成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
        }




    }
}
